package org.rency.common.mq.handler.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.lang.StringUtils;
import org.rency.common.mq.handler.MessageHandlerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageHandlerFactoryImpl implements MessageHandlerFactory{

	private static final Logger logger = LoggerFactory.getLogger(MessageHandlerFactoryImpl.class);
	
	private static MessageHandlerFactory factory = new MessageHandlerFactoryImpl();

	private ConcurrentMap<String, AbstractMessageHandler> messageHandlers = new ConcurrentHashMap<String, AbstractMessageHandler>();

	private MessageHandlerFactoryImpl() {
	}

	public static MessageHandlerFactory getInstance() {
		return factory;
	}

	public void addMessageHandler(String destination, AbstractMessageHandler messageHandler) {
		if (messageHandler == null){
			throw new IllegalArgumentException("Message handler cannot be null.");
		}
		this.messageHandlers.putIfAbsent(destination, messageHandler);
	}

	public AbstractMessageHandler getMessageHandler(String destination) {
		logger.info("Get message handler, destination is: " + destination);

		if (StringUtils.isBlank(destination))
			throw new IllegalArgumentException("Handler class name cannot be empty.");

		AbstractMessageHandler messageHandler = this.messageHandlers.get(destination);
		return messageHandler;
	}
	
}